package cn.csxw.openchina.utils;

import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.drawable.Drawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Handler;
import android.os.Looper;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import cn.csxw.openchina.base.BaseRefreshFragment;
import cn.csxw.openchina.constant.Constant;
import cn.csxw.openchina.dagger2.presenter.BasePresenter;
import cn.csxw.openchina.entity.ResultState;
import cn.csxw.openchina.interfaces.IOSChinaServer;

/**
 * 全局公共类, 封装一些公共公能
 *
 * @author JQ
 */
public class Global {
    public static SharedPreferences sp;

    public static Context mContext;

    public static float mDensity;

    public static float mScreenWidth;

    public static float mScreenHeight;
    public static IOSChinaServer mOsChinaServer;
    public static void init(Context context, IOSChinaServer osChinaServer) {
        mContext = context;
        mOsChinaServer = osChinaServer;
        sp = mContext.getSharedPreferences(Constant.USER_UID, Context.MODE_PRIVATE);
        initScreenSize();
    }

    private static void initScreenSize() {
        DisplayMetrics dm = mContext.getResources().getDisplayMetrics();
        mDensity = dm.density;
        mScreenHeight = dm.heightPixels;
        mScreenWidth = dm.widthPixels;
    }

    public static int dp2px(int dp) {
        return (int) (dp * mDensity);
    }

    public static View inflate(int layoutResID, ViewGroup parent) {
        return LayoutInflater.from(mContext).inflate(layoutResID, parent, false);
    }

    public static View inflate(int layoutResID) {
        return inflate(layoutResID, null);
    }

    private static Handler mHandler = new Handler(Looper.getMainLooper());

    public static Handler getMainHandler() {
        return mHandler;
    }

    /**
     * 判断当前线程是否是主线程
     *
     * @return true表示当前是在主线程中运行
     */
    public static boolean isUIThread() {
        return Looper.getMainLooper() == Looper.myLooper();
    }

    public static void runOnUIThread(Runnable run) {
        if (isUIThread()) {
            run.run();
        } else {
            mHandler.post(run);
        }
    }

    private static Toast mToast;

    /**
     * 可以在子线程中调用
     *
     * @param msg toast内容
     */
    public static void showToast(final String msg) {
        runOnUIThread(new Runnable() {
            @Override
            public void run() {
                if (mToast == null) {
                    mToast = Toast.makeText(mContext, msg, Toast.LENGTH_SHORT);
                }
                mToast.setText(msg);
                mToast.show();
            }
        });
    }


    /**
     * 查找一个布局中所有的按钮，并设置点击事件
     *
     * @param parent
     */
    public static void findButtonsAndSetOnClickListener(
            View parent, View.OnClickListener listener) {
        if (parent instanceof ViewGroup) {
            ViewGroup p = (ViewGroup) parent;
            for (int i = 0; i < p.getChildCount(); i++) {
                View child = p.getChildAt(i);
                if (child instanceof TextView || child instanceof ImageButton) {
                    // 给按钮设置点击事件
                    child.setOnClickListener(listener);
                } else if (child instanceof ViewGroup) {
                    findButtonsAndSetOnClickListener(child, listener);
                }
            }
        }
    }


    /**
     * BasePresenter回调方法的封装
     *
     * @param basePresenter
     * @param baseRefreshFragment
     */
    public static void onNetworkStateListener(BasePresenter basePresenter, final BaseRefreshFragment baseRefreshFragment) {
        basePresenter.setOnResultStateListener(new BasePresenter.OnResultStateListener() {
            @Override
            public void onStateError(Throwable t, ResultState errorState) {
                baseRefreshFragment.contentPager.loadDataOrRefreshData(errorState);
                baseRefreshFragment.loadMoreCompleted();
                baseRefreshFragment.mSrfLayout.setRefreshing(false);
            }

            @Override
            public void onStateSuccess(ResultState successState) {
                baseRefreshFragment.contentPager.loadDataOrRefreshData(successState);
                baseRefreshFragment.loadMoreCompleted();
                baseRefreshFragment.mSrfLayout.setRefreshing(false);
            }

            @Override
            public void onStateEmpty(ResultState emptyState) {
                baseRefreshFragment.contentPager.loadDataOrRefreshData(emptyState);
                baseRefreshFragment.loadMoreCompleted();
                baseRefreshFragment.mSrfLayout.setRefreshing(false);
            }
        });
    }

    //获取图片资源
    public  static Drawable getDrawable(int drawbleResID){
        return mContext.getResources().getDrawable(drawbleResID);
    }

    public static void setUserUid(String uid){
        SharedPreferences.Editor edit = sp.edit();
        edit.putString(Constant.USER_UID, uid);
        edit.commit();
    }
    public static String getUserUid(String key){
        return sp.getString(key, null);
    }
    public static void setCookie(String cookie){
        SharedPreferences.Editor edit = sp.edit();
        edit.putString(Constant.COOKIE, cookie);
        edit.commit();
    }
    public static String getCook(String key){
        return sp.getString(key, null);
    }

    /**
     * 判断网络是否可用
     *
     * @param context Context对象
     */
    public static Boolean isNetworkReachable(Context context) {
        ConnectivityManager cm = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo current = cm.getActiveNetworkInfo();
        if (current == null) {
            return false;
        }
        return (current.isAvailable());
    }
}
